package access

import (
	"jtdevice/app/hook"
	"jtdevice/configs"
	"jtdevice/util"
	"log"

	"github.com/dontls/xproto"

	_ "github.com/dontls/xproto/ho"
	_ "github.com/dontls/xproto/jt"
	_ "github.com/dontls/xproto/ttx"
)

func AccessHandler(b []byte, a *xproto.Access) (interface{}, error) {
	switch a.LinkType {
	case xproto.LinkSignal:
		hook.Publish(hook.Msg().Online, a)
		return nil, nil
	case xproto.LinkFileTransfer:
		t := xproto.FileOfSess(a.Session)
		if t.Action == xproto.ActUpload {
			return nil, xproto.UploadFile(a, t.FileName, true)
		}
		return xproto.DownloadFile(configs.Public.Abs(t.FileName), nil)
	default:
		return nil, xproto.ErrUnSupport
	}
}

func DroppedHandler(v interface{}, a *xproto.Access, err error) {
	switch a.LinkType {
	case xproto.LinkFileTransfer:
		t := xproto.FileOfSess(a.Session)
		if t.Action == xproto.ActUpload {
			xproto.DownloadFile("", v)
		}
	case xproto.LinkSignal:
		log.Println(err)
		hook.Publish(hook.Msg().Online, a)
	}
}

func StatusHandler(tag string, arg interface{}, s *xproto.Status) {
	if s == nil {
		return
	}
	hook.Publish(hook.Msg().Status, s)
}

func AlarmHandler(b []byte, arg interface{}, a *xproto.Alarm) {
	if a.Type >= 0x500 {
		return
	}
	// xproto.LogAlarm(b, arg, a)
	hook.Publish(hook.Msg().Alarm, a)
}

func EventHandler(data []byte, arg interface{}, e *xproto.Event) {
	xproto.LogEvent(data, arg, e)
	if configs.FtpURL == "" {
		return
	}
	ftp := &xproto.FtpTransfer{
		Action:  xproto.ActDownload,
		Session: e.Session,
		FtpURL:  configs.FtpURL,
	}
	switch e.Type {
	case xproto.EntFileLittle:
		v := e.Data.(*xproto.EventFileLittle)
		ftp.FileSrc = v.FileName
		ftp.FileDst = util.FilePath(v.FileName, e.DeviceNo)
		ftp.FileType = v.FileType
	case xproto.EntFileCapture:
		v := e.Data.(*xproto.EventFileCapture)
		ftp.FileSrc = v.FileName
		ftp.FileDst = util.FilePicPath(v.FileName, e.DeviceNo)
		ftp.FileType = v.FileType
	default:
		return
	}
	xproto.SyncSend(xproto.ReqFtpTransfer, ftp, nil, e.DeviceNo)
}
